package com.iqiju.guagua.redtone.video.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiju.guagua.redtone.video.common.Results;
import com.iqiju.guagua.redtone.video.model.WxMiniUser;
import com.iqiju.guagua.redtone.video.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtHandler extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(JwtUtils.HEADER_TOKEN_NAME);
        /* token为null直接走登录的过滤器，不为空走下面 */
        if (token!=null&&token.trim().length()>0) {
            String tokenBody = null;
            try {
                tokenBody = JwtUtils.testJwt(token);
            } catch (Exception e) {
                log.error("token 验证异常  token={}", token);
                log.error(e.getMessage(), e);
            }
            /* 从token中取出用户信息，放在上下文中 */
            if (tokenBody!=null&&tokenBody.trim().length()>0){
                JSONObject jwtObject = JSON.parseObject(tokenBody);
                Long exp = jwtObject.getLong("exp");
                if (exp<System.currentTimeMillis()){
                    HttpServletResponse res = (HttpServletResponse) response;
                    res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    res.getWriter().write(JSON.toJSONString(Results.loginExpireError()));
                    log.warn("登录过期或者未登录=============");
                    return;
                }
                JSONObject user = jwtObject.getJSONObject("user");
                WxMiniUser wxMiniUser = JSON.toJavaObject(user,WxMiniUser.class);
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(wxMiniUser,null,wxMiniUser.getAuthorities()));
            }else{
                HttpServletResponse res = (HttpServletResponse) response;
                res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                res.getWriter().write(JSON.toJSONString(Results.tokenError()));
                log.warn("token错误===========");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}